/*
 * 文 件 名:  JwtAuthenticationFilter
 * 版    权:
 * 描    述:  <描述>
 * 修 改 人:  redName
 * 修改时间:  2022/5/4
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.zj003.framework.security;

import com.zj003.common.domain.model.LoginUser;
import com.zj003.framework.service.TokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <功能详细描述>
 * 认证过滤器
 *
 * @author ReaName
 * @version [版本号, 2022/5/4]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final TokenService tokenService;


    /**
     * 认证方法
     *
     * @param request  请求信息
     * @param response 响应
     * @param chain    过滤器链
     * @author RedName
     * {@code @date} 2022/5/6 4:07
     */
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain) throws ServletException, IOException {
        tokenService.getLoginUserOptional(request).ifPresent(loginUser -> {
            tokenService.verifyToken(loginUser);
            Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        });
        chain.doFilter(request, response);

    }
}
